// packageA/pages/goodsStorageInAdd/goodsStorageInAdd.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';
const util = require('../../../utils/util');
import Base64 from '../../../utils/Base64.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj: null,
    //传参来的id
    id: null,
    //是否是修改
    isEdit: false,
    //修改信息回显
    editInfo: {},
    //提交按钮禁用
    disabled: false,
    //避免表单重复提交
    code: null,
    //物资列表
    goods: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      code: Base64.encode(new Date() + app.globalData.userInfo.userName)
    })

    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);
      console.log('添加入库传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj
      })

      if(paramObj.id){
        this.setData({
          id: paramObj.id,
          isEdit: true
        })
        //获取修改数据
        this.getInfo();

      }else{
        //查询仓库信息
        this.getStorageInfo();

        //添加时初始化数据
        let user=app.globalData.userInfo;
        let staff='editInfo.staff';

        this.setData({
          //入库人员
          [staff]: {
            id: user.id,
            name: user.userName,
            phone: user.personalPhone
          }
        })
      }
    }
  },

  //提交表单##
  confirmForm(e){
    //避免表单重复提交-先禁用按钮
    this.setData({
      disabled:true
    })

    let obj=e.detail.value;
    let detail=e.detail.target.dataset.detail;
    let td=this.data;
    let editInfo=td.editInfo;
    let goods=td.goods;
    let user=app.globalData.userInfo;

    //物资
    let goodsList=[];
    if(goods.length){
      //无num的赋值1
      goods.forEach(item => {
        if(!item.num){
          item.num=1;
        }
        goodsList.push({
          goods: item,
          num: item.num
        });
      });
    }else{
      Toast.fail('请添加物资');
      return;
    }

    //权限
    let authArr=[user.depart, user.departObj[0].companyId, user.departObj[0].regionId, 1,1938];
    authArr=util.arrayRepeatEmpty(authArr);

    //单号
    let times = util.currentTimestamp();

    let dataObj={
      requestToken: td.code,
      id: td.id,
      //物资列表
      goodsList: goodsList,
      //备注
      remark: obj.remark.trim()
    }

    //添加时
    if(!td.isEdit){
      //入库单号
      dataObj.orderNo = 'IS-'+times;
      //入库人员
      dataObj.staff = editInfo.staff;
      //仓库
      dataObj.storage = editInfo.storage;
      //平台
      dataObj.appId = [app.globalData.myAppId];
      //数据权限
      dataObj.dataAuthority ={
        depart: authArr
      };
      //状态
      dataObj.state = 0  
    }

    let param={
      className: 'requisitionInStorage',
      data: dataObj
    }    

    // console.log(param.data);
    // return;  

    if(detail==1){
      //只保存
      this.saveStorageIn(param,1);
    }else if(detail==2){
      //保存并入库
      this.onInStorage(param);
    }  
  },

  //保存入库单
  saveStorageIn(param,flag){
    //避免表单重复提交
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '数据提交中...'
    });

    CommonService.goSave(param).then(res=>{
      this.setData({
        disabled:false
      })
      if (res.statusCode == 200 && res.data.success == true){
        if(flag==1){
          Toast.success('已保存');

          setTimeout(() => {
            //返回列表页并刷新数据
            this.backAndRefresh();
          }, 1000);
        }else if(flag==2){
          //入库
          this.inStorage(param.data);
        }
      }else if(res.statusCode==202){
        Toast.fail('您操作太快了,请勿重复提交');
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })
  },

  //获取修改数据
  getInfo(){
    let param = {
      isAuth: false,
      className: 'requisitionInStorage',
      data: {
        id:this.data.id,
        selectFields: ['id','storage','staff','remark','goodsList']
      }
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result[0];
        console.log('入库回显');
        console.log(result);

        //物资列表
        let arr=[];
        if(result.goodsList && result.goodsList.length){
          result.goodsList.forEach(item => {
            item.goods.num=item.num;
            arr.push(item.goods);
          });
        }

        this.setData({
          editInfo: result,
          goods: arr
        })
      }
    }).catch((error) => {
    })
  },

  //返回列表页并刷新数据
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];

    prevPage.refreshListAndPage();
    wx.navigateBack();
  },

  //添加物资
  goToAdd(){
    this.setData({
      disabled: false
    })

    let goods=this.data.goods;
    let ids=[];

    if(goods.length){
      goods.forEach(item => {
        ids.push(item.id);
      });
    }

    let obj={
      ids: ids
    }
    wx.navigateTo({
      url: "/packageA/pages/goodsList/goodsList?paramObj="+JSON.stringify(obj)
    })
  },

  //获取物资
  getProduct(ids){
    let param = {
      isAuth: true,
      className: 'clientProducts',
      data: {
        searchAll: true,
        id: ids,
        selectFields: ['id','name','pic','factory','spec','params','classify','unit','code','price'],
        sort: {
          id: -1
        }
      }
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;
        console.log('物资列表');
        console.log(result);

        //处理数量
        let goods=this.data.goods;
        if(goods.length){
          result.forEach(item => {
            for(let i=0;i<goods.length;i++){
              if(item.id==goods[i].id){
                item.num=goods[i].num
              }
            }
          });
        }

        this.setData({
          goods: result
        })
      }
    }).catch((error) => {
    })
  },

  //物资数量
  onChangeNum(e) {
    let list=this.data.goods;
    let dataset=e.currentTarget.dataset;

    list.forEach((item,index) => {
      if(index==dataset.index){
        item.num=e.detail;
      }
    });

    this.setData({
      goods: list,
      disabled: false
    })
  },

  //删除物资
  ondeleteLoop(e){
    Dialog.confirm({
      title: '确认删除物资吗',
      confirmButtonText:'确认',
      cancelButtonText:'不删除了'
    }).then(() => {
      let list=this.data.goods;
      let detail=e.currentTarget.dataset.detail;
      let arr=[];

      list.forEach((item) => {
        if(item.id!=detail.id){
          arr.push(item);
        }
      });

      this.setData({
        goods: arr,
        disabled: false
      })
    }).catch(() => {
    });
  },

  //查询仓库信息
  getStorageInfo(){
    let param = {
      isAuth: true,
      className: 'clientStorage',
      data: {
        searchAll: true,
        selectFields: ['id','name']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result[0];      
        let storage='editInfo.storage';

        this.setData({
          [storage]: {
            id: result.id,
            name: result.name 
          }
        })
      }
    }).catch((error) => {
    })
  },

  //输入备注时
  onInputRemark() {
    this.setData({
      disabled: false
    })
  },

  //点击保存并入库
  onInStorage(param){
    Dialog.confirm({
      title: '入库后单据无法修改或删除, 是否继续？',
      confirmButtonText:'确定入库',
      cancelButtonText:'只保存'
    }).then(() => {
      this.saveStorageIn(param,2);
    }).catch(() => {
      this.saveStorageIn(param,1);
    });
  },

  //入库
  inStorage(detail){
    let param={
      id: detail.id,
      orderNo: detail.orderNo,
      inStorageTime: new Date(),
      staff: detail.staff,
      goodsList: detail.goodsList,
      remark: detail.remark,
      storage: detail.storage,
      state: 0,
      dataAuthority: detail.dataAuthority
    }
    
    // console.log(param);
    // return;

    CommonService.materialInStorage(param).then(res=>{
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('已入库');

        setTimeout(() => {
          //返回列表页并刷新数据
          this.backAndRefresh();
        }, 1000);
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})